package com.example.hoop.slice;

import ai.djl.Application;
import ai.djl.modality.cv.output.DetectedObjects;
import ai.djl.modality.cv.util.BufferedImageUtils;
import ai.djl.repository.zoo.Criteria;
import ai.djl.repository.zoo.ModelZoo;
import ai.djl.repository.zoo.ZooModel;
import ai.djl.training.util.ProgressBar;
import ai.djl.util.Progress;
import com.example.hoop.ResourceTable;
import com.example.hoop.util.Mythread;


import ohos.aafwk.ability.AbilitySlice;

import ohos.aafwk.content.Intent;

import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;

import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import ohos.net.NetHandle;
import ohos.net.NetManager;

import ohos.wifi.IpInfo;
import ohos.wifi.WifiDevice;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import java.net.*;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import java.util.Optional;


public class MainAbilitySlice extends AbilitySlice {
    private static String HOST = "10.161.116.158";
    private static String TAG = "测试";
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, TAG);
    private final static int PORT = 10006;
    String s = "Nothing";
    private TextField iptf;
    private Text iptext;
    private Text text;
    private TextField sendtf;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main2);

        //启动按键
        Button btn = findComponentById(ResourceTable.Id_btn);
        //消息文本
        text = findComponentById(ResourceTable.Id_text);
        //接受ip地址
        iptf = findComponentById(ResourceTable.Id_textfield);
        //本机IP
        iptext = findComponentById(ResourceTable.Id_localip);
        //发送信息
        sendtf = findComponentById(ResourceTable.Id_sendfield);

        iptext.setText(getLocalIpAddress() + " " + PORT);
        btn.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                sendMessage();
            }
        });
    }

    private void sendMessage() {
        Mythread.inBG(new Runnable() {
            @Override
            public void run() {
                NetManager netManager = NetManager.getInstance(null);

                if (!netManager.hasDefaultNet()) {
                    HiLog.error(LABEL_LOG,
                            "netManager.hasDefaultNet() failed");

                    return;
                }

                NetHandle netHandle = netManager.getDefaultNet();

                // 通过Socket绑定来进行数据传输
                DatagramSocket socket = null;

                try {
                    //从textfield组件获取用户输入的对端ip地址
                    HOST = iptf.getText();

                    InetAddress address = netHandle.getByName(HOST);
                    socket = new DatagramSocket();
                    netHandle.bindSocket(socket);

                    /*至此 已绑定对端Socket*/

                    //从一个textfield组件获取用户输入的要发送的信息。
                    String data = new String(sendtf.getText());

                    /************增加新的编码方式***************/

                    /************增加新的编码方式***************/

                    //这里默认还是发送至对端的10006端口
                    DatagramPacket request = new DatagramPacket(data.getBytes(
                            "UTF-8"), data.length(),
                            address, PORT);
                    // buffer赋值
                    // 发送数据

                    socket.send(request);
                    HiLog.info(LABEL_LOG, "send data: " + data);
                } catch (IOException e) {
                    HiLog.error(LABEL_LOG, "send IOException: ");
                } finally {
                    if (null != socket) {
                    }
                }
            }
        });
    }

    private void StartServer() {
        Mythread.inBG(new Runnable() {
            @Override
            public void run() {
                HiLog.info(LABEL_LOG, "StartServer run");

                NetManager netManager = NetManager.getInstance(null);

                if (!netManager.hasDefaultNet()) {
                    HiLog.error(LABEL_LOG,
                            "netManager.hasDefaultNet() failed");

                    return;
                }

                NetHandle netHandle = netManager.getDefaultNet();
                DatagramSocket socket = null;

                // 通过Socket绑定来进行数据传输
                try {
                    HiLog.info(LABEL_LOG, "wait receive data");

                    //通过getLocalIpAddress()快速获取本机的IP地址
                    InetAddress address = netHandle.getByName(getLocalIpAddress());
                    //端口号+主机地址
                    socket = new DatagramSocket(10006, address);
                    netHandle.bindSocket(socket);
                    /*至此绑定Socket结束*/
                    HiLog.info(LABEL_LOG, "绑定成功");

                    /*监听函数*/
                    byte[] buffer = new byte[1024];
                    DatagramPacket response = new DatagramPacket(buffer,
                            buffer.length);

                    while (true) {
                        //接收数据
                        socket.receive(response);

                        int len = response.getLength();
                        HiLog.info(LABEL_LOG, "接收成功");
                        //将数据打印到屏幕上
                        s = new String(buffer, StandardCharsets.UTF_8).substring(0,
                                len);
                        Mythread.inUI(new Runnable() {
                            @Override
                            public void run() {
                                //一个textfield组件
                                text.setText(s);
                            }
                        });

                        HiLog.info(LABEL_LOG, "receive data: " + s);
                    }
                } catch (IOException e) {
                    HiLog.error(LABEL_LOG, "rev IOException: ");
                }
            }
        });
    }

    private String getLocalIpAddress() {
        WifiDevice wifiDevice = WifiDevice.getInstance(getContext());
        Optional<IpInfo> ipInfo = wifiDevice.getIpInfo();
        int ip = ipInfo.get().getIpAddress();

        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." + ((ip >> 24) & 0xFF);
    }

    @Override
    public void onActive() {
        super.onActive();
        StartServer();
    }

    public static String unicode(String str) {
        //存放结果
        StringBuffer res = new StringBuffer();
        //将发送的信息转换成字符数组
        char[] tmp = str.toCharArray();
        //将字符转换成unicode编码
        String unicode = null;
        for (int i = 0; i < tmp.length; i++) {
           //10-16进制的转换
            unicode = Integer.toHexString(tmp[i]);
            //长度小于2的时候，00补齐
            if (unicode.length() <= 2) {
                unicode = "00" + unicode;
            }
            //转换成 /u形式的unicode编码
            res.append("\\u" + unicode);
        }
      //返回unicode编码的字符串形式
        return res.toString();
    }

    public static String decodeUnicode2(String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();

        while (start > -1) {
            end = dataStr.indexOf("\\\\u", start + 2);

            String charStr = null;

            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }

            char letter = (char) Integer.parseInt(charStr, 16);
            buffer.append(new Character(letter).toString());
            start = end;
        }

        return buffer.toString();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
